package com.waji.activity;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClientOption;
 

import com.waji.activity.R;
import com.waji.dao.CreatQRcode;
import com.waji.dao.StartVideo;
import com.waji.dao.TakePhoto;
import com.waji.dao.TakePicture;
import com.waji.dao.UpdateManager;
import com.waji.local.NextDay;
import com.waji.local.SaveLocation;
import com.waji.local.SharedPrefer;
import com.waji.http.SendImage;
import com.waji.utils.LocationService;
import com.waji.interfac.MyLeanCloudApp;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.hardware.Camera;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.os.SystemClock;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.telephony.TelephonyManager;
import android.text.format.Formatter;
import android.view.KeyEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class MainActivity extends Activity implements OnPageChangeListener {

	private TextView tv_number;
	private TextView tv_location;
	private TextView tv_GyroscopeX;
	private TextView tv_GyroscopeY;
	private TextView tv_GyroscopeZ;
	private TextView tv_state;
	private EditText editText1;

	private SensorManager sensorManager;
	private Sensor sensor;
	private LocationService locService;
	private ImageView ib_qrcode;
	private SurfaceView mSurfaceview;

	int number;
	TakePicture picture;
	TakePhoto photo;
	StartVideo video1;
	Camera camera;
	String info;

	private TextView tv_gengxing;
	public static int version, serverVersion;
	public static String versionName, serverVersionName, downloadResult;

	private ProgressBar proBar;
	public static receiveVersionHandler checkhandler;
	private UpdateManager manager = UpdateManager.getInstance();
	
	private Handler locHander = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			int what = msg.getData().getInt("what");
			if (what == 1) {
				try {
					BDLocation location = msg.getData().getParcelable("loc");
					final double longitude = location.getLongitude();
					final double latitude = location.getLatitude();
					String AddrStr = location.getAddrStr();

					SharedPrefer
							.SaveLatitude(getApplicationContext(), latitude);
					SharedPrefer.SaveLongitude(getApplicationContext(),
							longitude);
					SharedPrefer.SaveAddress(getApplicationContext(), AddrStr);
					SaveLocation.save(getApplicationContext(), longitude,
							latitude);

					String lng = "经度: " + longitude;
					String lat = "纬度 :" + latitude;

					tv_location.setText(AddrStr);

				} catch (Exception e) {
				}
			}
			if (what == 0) {
				String AddrStr = SharedPrefer
						.ReadAddress(getApplicationContext());
				tv_location.setText(AddrStr);

			}
		}
	};

	private Handler handler1 = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				try {

					SharedPrefer.SaveService(getApplicationContext(), "stop");
					String service = SharedPrefer
							.ReadService(getApplicationContext());
				} catch (Exception e) {
					e.printStackTrace();
				}
				tv_number.setTextColor(Color.BLUE);
				break;
			case 0:
				break;
			}
		}
	};

	private List<ImageView> imageViewList;
	private ViewPager mViewPager;
	private boolean isLoop = true;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		registerReceiver(mbatteryReceiver, new IntentFilter(
				Intent.ACTION_BATTERY_CHANGED));
		TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		info = tm.getDeviceId();
		Register reg = new Register();
		reg.register(info);

		InitOther other = new InitOther();
		other.init(getApplicationContext(), info);

		new Thread(new Runnable() {
			@Override
			public void run() {
				while (isLoop) {
					SystemClock.sleep(5 * 1000);
					handler.sendEmptyMessage(0);
				}
			}
		}).start();
		initView();
		init();
		initLocation();
		getQRcodeimage();
		
		tv_gengxing = (TextView) findViewById(R.id.tv_gengxing);
		proBar = (ProgressBar) findViewById(R.id.progressBar_id);
		version = manager.getVersion(this);
		versionName = manager.getVersionName(this);
 
		checkhandler = new receiveVersionHandler();
		manager.CheckVersion(this);
	}
	public class receiveVersionHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				proBar.setProgress(msg.arg1);
				proBar.setVisibility(View.VISIBLE);
				tv_gengxing.setVisibility(View.VISIBLE);
				if (msg.arg1 == 100) {
					Intent intent = new Intent("android.intent.action.VIEW");
					intent.addCategory("android.intent.category.DEFAULT");
					String type = "application/vnd.android.package-archive";
					Uri data = Uri.fromFile(new File(Environment
							.getExternalStorageDirectory() + "/nihao.apk"));
					intent.setDataAndType(data, type);
					startActivityForResult(intent, 0);
				}
				proBar.setVisibility(View.VISIBLE);
				break;
			case 0:
				 
				break;
			}

		}
	}
	public void initView() {
		mViewPager = (ViewPager) findViewById(R.id.viewpager);
		prepareData();
		ViewPagerAdapter adapter = new ViewPagerAdapter();
		mViewPager.setAdapter(adapter);
		mViewPager.setOnPageChangeListener(this);
		int n = Integer.MAX_VALUE / 2 % imageViewList.size();
		int itemPosition = Integer.MAX_VALUE / 2 - n;
		mViewPager.setCurrentItem(itemPosition);
	}

	private void prepareData() {
		imageViewList = new ArrayList<ImageView>();
		int[] imageResIDs = getImageResIDs();
		ImageView iv;
		for (int i = 0; i < imageResIDs.length; i++) {
			iv = new ImageView(this);
			iv.setBackgroundResource(imageResIDs[i]);
			imageViewList.add(iv);
		}
	}

	private int[] getImageResIDs() {
		return new int[] { R.drawable.waji, R.drawable.wajueji2,
				R.drawable.wajueji3, R.drawable.wajueji5, R.drawable.wajueji6 };
	}

	class ViewPagerAdapter extends PagerAdapter {

		@Override
		public int getCount() {
			return Integer.MAX_VALUE;
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			container.removeView(imageViewList.get(position
					% imageViewList.size()));
		}

		@Override
		public Object instantiateItem(ViewGroup container, int position) {
			container
					.addView(imageViewList.get(position % imageViewList.size()));
			return imageViewList.get(position % imageViewList.size());
		}
	}

	@Override
	public void onPageScrollStateChanged(int arg0) {
	}

	@Override
	public void onPageScrolled(int arg0, float arg1, int arg2) {
	}

	@Override
	public void onPageSelected(int position) {
	}

	public void setListener() {

	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		isLoop = false;
	}

	private BroadcastReceiver mbatteryReceiver = new BroadcastReceiver() {
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			String battery;
			if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
				int status = intent.getIntExtra("status",
						BatteryManager.BATTERY_STATUS_UNKNOWN);
				int batteryLevel = intent.getIntExtra(
						BatteryManager.EXTRA_LEVEL, 0);
				if (status == BatteryManager.BATTERY_STATUS_CHARGING
						|| batteryLevel == 100) {
					battery = "充电中  电量：" + batteryLevel + "%";
					getWindow().addFlags(
							WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
				} else {
					battery = "未充电  电量：" + batteryLevel + "%";
					getWindow().clearFlags(
							WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
				}

				try {
					SharedPrefer.SaveBattery(context, battery);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
				|| keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
			String service = SharedPrefer.ReadService(getApplicationContext());
			if (service.equals("stop")) {
				starpicture();
				return true;
			}
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			this.finish();
		}
		return super.onKeyDown(keyCode, event);
	}

	public void photostart(View view) {
		String service = SharedPrefer.ReadService(getApplicationContext());
		if (service.equals("stop")) {
			starpicture();
		} else
			return;
	}

	public void starpicture() {
		try {
			SharedPrefer.SaveService(getApplicationContext(), "star");
		} catch (Exception e) {
			e.printStackTrace();
		}
		picture = new TakePicture();
		photo = new TakePhoto();
		video1 = new StartVideo();

		number = SharedPrefer.ReadNumber(getApplicationContext());
		number = number + 1;
		String numstring = Integer.toString(number);
		tv_number.setText(numstring);
		tv_number.setTextColor(Color.RED);
		new Thread() {
			@Override
			public void run() {
				Message msg = new Message();
				super.run();
				try {
					picture.Startpicture(getApplicationContext(), 1);
					Thread.sleep(1000);

					photo.Startphoto(getApplicationContext(), 1);
					Thread.sleep(2000);

					SendImage image = new SendImage();
					image.send(getApplicationContext(), 1);
					SharedPrefer.SaveNumber(getApplicationContext(), number);

					video1.video(mSurfaceview, getApplicationContext());
					Thread.sleep(21 * 1000);

					System.out.println("验证码1");
					msg.what = 1;
					handler1.sendMessage(msg);

				} catch (Exception e) {
					System.out.println("异常" + e);
					e.printStackTrace();
					msg.what = 0;
					handler1.sendMessage(msg);
				}
			}
		}.start();

	}

	public void getQRcodeimage() {

		CreatQRcode code = new CreatQRcode();
		Bitmap bitmap = code.creatQRcode(getApplicationContext(), info);
		ib_qrcode.setImageBitmap(bitmap);
	}

	public void init() {
		tv_number = (TextView) findViewById(R.id.tv_number);
		tv_location = (TextView) findViewById(R.id.tv_location);

		ib_qrcode = (ImageView) findViewById(R.id.ib_qrcode);
		mSurfaceview = (SurfaceView) findViewById(R.id.sv_main_video);

		tv_GyroscopeX = (TextView) findViewById(R.id.tv_GyroscopeX);
		tv_GyroscopeY = (TextView) findViewById(R.id.tv_GyroscopeY);
		tv_GyroscopeZ = (TextView) findViewById(R.id.tv_GyroscopeZ);
		tv_state = (TextView) findViewById(R.id.tv_state);
		editText1 = (EditText) findViewById(R.id.editText1);

		sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
		sensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);

		number = SharedPrefer.ReadNumber(getApplicationContext());
		String numstring = Integer.toString(number);
		tv_number.setText(numstring);

	}

	public void initLocation() {
		String location = SharedPrefer.ReadAddress(getApplicationContext());
		if (location != null) {
			tv_location.setText(location);
		}

		locService = ((MyLeanCloudApp) getApplication()).locationService;
		LocationClientOption mOption = locService
				.getDefaultLocationClientOption();
		mOption.setLocationMode(LocationClientOption.LocationMode.Battery_Saving);
		mOption.setCoorType("bd09ll");
		locService.setLocationOption(mOption);
		locService.registerListener(listener1);
		locService.start();

	}

	BDLocationListener listener1 = new BDLocationListener() {
		@Override
		public void onReceiveLocation(BDLocation location) {
			Bundle locData = new Bundle();
			Message locMsg = locHander.obtainMessage();
			if (location != null
					&& (location.getLocType() == 161 || location.getLocType() == 66)) {
				locData.putInt("what", 1);
				locData.putParcelable("loc", location);
				locMsg.setData(locData);
				locHander.sendMessage(locMsg);
			} else {
				locData.putInt("what", 0);
				locMsg.setData(locData);
				locHander.sendMessage(locMsg);
			}
		}

		public void onConnectHotSpotMessage(String s, int i) {
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		sensorManager.registerListener(listener, sensor,
				SensorManager.SENSOR_DELAY_NORMAL);
	}

	private SensorEventListener listener = new SensorEventListener() {
		public void onSensorChanged(SensorEvent e) {
			String a = editText1.getText().toString().trim();
			String state = "暂停";
			float xyz = Float.parseFloat(a);
			float x = Math.abs(e.values[0]);
			float y = Math.abs(e.values[1]);
			float z = Math.abs(e.values[2]);
			tv_GyroscopeX.setText("X方向 " + x);
			tv_GyroscopeY.setText("Y方向 " + y);
			tv_GyroscopeZ.setText("Z方向 " + z);
			try {
				if (x > xyz || y > xyz || z > xyz) {
					state = "工作";
					SharedPrefer.SaveState(getApplication(), "工作");
				} else {
					state = "暂停";
					SharedPrefer.SaveState(getApplication(), "暂停");
				}
				tv_state.setText(state);
			} catch (Exception e1) {
				e1.printStackTrace();
			}
		}

		public void onAccuracyChanged(Sensor arg0, int arg1) {
		}
	};

}
